package com.codedancer.campus.client.factory;


import static com.codedancer.campus.enums.SystemMessageType.FOLLOW_USER;

import com.codedancer.campus.client.handler.SystemMessageHandler;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.enums.SystemMessageType;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SystemMessageFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;
    private static final Map<SystemMessageType, SystemMessageHandler> SYSTEM_MESSAGE_HANDLER_MAP = new HashMap<>();

    /**
     * 根据系统消息类型获取对应的处理器
     *
     * @param messageType
     * @return
     */
    public SystemMessageHandler getSystemMessageHandler(Integer messageType) {
        if (Objects.equals(FOLLOW_USER.getValue(), messageType)) {
            // 关注用户
            return SYSTEM_MESSAGE_HANDLER_MAP.get(FOLLOW_USER);
        } else {
            throw new BusinessException("系统消息类型不正确!");
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(SystemMessageHandler.class).values().forEach(bean -> {
            SYSTEM_MESSAGE_HANDLER_MAP.put(bean.getSystemMessageType(), bean);
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
